# -*- coding: utf-8 -*-
import mod.server.extraServerApi as serverApi
from mod.server.system.serverSystem import ServerSystem

from dwjjCoreServerScripts.common import logger


class RedstoneModule(object):

    def __init__(self, serverSystem, config):
        # type: (ServerSystem, dict) -> None
        self.serverSystem = serverSystem
        self.config = config
        # 判断该系统是否启用
        if not config["enable"]:
            self.enable = False
            return
        # 初始化引擎工厂
        self.InitComp()
        # 初始化基础参数
        self.InitSetting()
        # 注册监听器
        self.InitListener()

    def InitComp(self):
        self.blockInfoComp = serverApi.GetEngineCompFactory().CreateBlockInfo(serverApi.GetLevelId())

    def InitSetting(self):
        pass

    def InitListener(self):
        # 活塞相关
        self.pistonLimitDict = self.config["pistonLimit"]
        if self.pistonLimitDict["enable"]:
            self.serverSystem.ListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(), "PistonActionServerEvent", self, self.OnPistonAction, 0)

    # 活塞事件
    def OnPistonAction(self, e):
        dim = e["dimensionId"]
        # 方块列表
        for blockPos in e["blockList"]:
            blockDict = self.blockInfoComp.GetBlockNew(tuple(blockPos), dim)
            if blockDict is None:
                continue
            if blockDict["name"] in self.pistonLimitDict["blocks"]:
                e["cancel"] = True
                return
        # 被破坏的方块列表
        for blockPos in e["breakBlockList"]:
            blockDict = self.blockInfoComp.GetBlockNew(tuple(blockPos), dim)
            if blockDict is None:
                continue
            if blockDict["name"] in self.pistonLimitDict["blocks"]:
                e["cancel"] = True
                return
        # 实体列表
        for entityId in e["entityList"]:
            entityComp = serverApi.GetEngineCompFactory().CreateEngineType(entityId)
            if entityComp.GetEngineTypeStr() in self.pistonLimitDict["entities"]:
                e["cancel"] = True
                return
